<template>
	<view class="fenxall">
		<view class="title" @click="hidefx" >
			<canvas class="canvas-poster" id="canvasPoster" :style="{width:(300*systemInfo.pixelRatio)+'px',height: (521*systemInfo.pixelRatio)+'px'}" canvas-id="canvasPoster"></canvas>
			<image :src="poster" class="poster-img" @click="previewImg" :style="{height:521+'px'}">
			<view @click="savePoster" class="save-btn">
				保存图片
			</view>
		</view>
	</view>
</template>

<script>
	export default{
		props:['shareInfo'],
		data(){
			return{
				width:300,
				height:521 ,
				poster:'',
				systemInfo:{},
				shareInfos:{},
				dhlh:0
			}
		},
		mounted() {
			var that=this;
			this.shareInfos = JSON.parse(this.shareInfo);
			uni.getSystemInfo({
			  success (res) {
					that.systemInfo=res;
				}
			})
			uni.showToast({
				title: '准备中...',
				icon:'loading',
				duration:3000
			});
			var query = uni.createSelectorQuery().in(this);
			setTimeout(function(){
				query.select('#canvasPoster').boundingClientRect((res) => {
					// 返回值包括画布的实际宽高
					that.drawImage(res)
				}).exec()
			},3000)
		},
		methods:{
			hidefx(){
				uni.$emit('schb',{
					json:'',
					show:false
				})
			},
			drawImage (canvasAttrs) {
				console.log(this.shareInfos)
				var pixelRatio=this.systemInfo.pixelRatio
			    let ctx = uni.createCanvasContext('canvasPoster', this)
			    let canvasW = canvasAttrs.width // 画布的真实宽度
			    let canvasH = canvasAttrs.height //画布的真实高度
			    // 头像和二维码大小都需要在规定大小的基础上放大像素比的比例后面都会 *this.systemInfo.pixelRatio
				//y22,x15
				//头像
			    let headerW = 31*pixelRatio
			    let headerX = 21*pixelRatio
			    let headerY = 380*pixelRatio
				//二维码
			    let qrcodeW = 69 *pixelRatio
			    let qrcodeX = 210*pixelRatio
			    let qrcodeY = 435*pixelRatio
				//商品图片
				let typimgW = 300*pixelRatio
				let typimgh = 192*pixelRatio
				let typimgX = 0
				let typimgY = 0
				//绘制商品图片
				ctx.drawImage(this.shareInfos.typeImg, typimgX, typimgY, typimgW, typimgh)
				ctx.save()
				// 绘制下半部分背景
				ctx.setFillStyle('#fff')
				ctx.fillRect(typimgX, 192*pixelRatio, typimgW, 354*pixelRatio)
				ctx.save()
				// 将头像画到画布上
				// 控制头像为圆形
				// ctx.setStrokeStyle('rgba(0,0,0,.2)') //设置线条颜色，如果不设置默认是黑色，头像四周会出现黑边框
				// ctx.arc(headerX + headerW / 2, headerY + headerW / 2, headerW / 2, 0, 2 * Math.PI)
				// ctx.stroke()
				// //画完之后执行clip()方法，否则不会出现圆形效果
				// ctx.clip()
				// 头像
				ctx.drawImage(this.shareInfos.headerImg, headerX, headerY, headerW, headerW)
				ctx.save()
				// 用户名
				ctx.setFontSize(13*pixelRatio)
				ctx.setFillStyle('#000')
				ctx.fillText(this.shareInfos.userName, 62*pixelRatio, 400*pixelRatio)
				//绘制价格
				ctx.setFontSize(13*pixelRatio)
				ctx.setFillStyle('#ED5934')
				ctx.fillText('¥', 21*pixelRatio, 280*pixelRatio)
				ctx.setFontSize(16*pixelRatio)
				ctx.fillText(this.shareInfos.salePrice, 35*pixelRatio, 280*pixelRatio)
				ctx.save()
				// 标题
				// ctx.setFontSize(17)
				// ctx.setFillStyle('#000')
				// ctx.fillText(this.shareInfos.name,17, 220)
				var t=this.shareInfos.name
				this.drawText(ctx,t,21*pixelRatio,220*pixelRatio,250*pixelRatio,17*pixelRatio,22*pixelRatio,'#000');
				ctx.save()
				// 地址
				var t=this.shareInfos.des
				this.drawText(ctx,t,21*pixelRatio,300*pixelRatio,250*pixelRatio,13*pixelRatio,18*pixelRatio,'#999');
				ctx.save()
			    // 绘制二维码
				ctx.setFillStyle('#f5f5f5')
				ctx.fillRect(0, 420*pixelRatio, 300*pixelRatio, 1*pixelRatio)
				ctx.save()
				ctx.drawImage(this.shareInfos.logo, 21*pixelRatio, 437*pixelRatio, 130*pixelRatio, 35*pixelRatio)
				ctx.save()
				ctx.setFontSize(13*pixelRatio)
				ctx.setFillStyle('#999')
				ctx.fillText('长按识别二维码 查看完整内容', 22*pixelRatio, 495*pixelRatio)
			    ctx.drawImage(this.shareInfos.qrcode, qrcodeX, qrcodeY, qrcodeW, qrcodeW)
			    ctx.save()
			    ctx.draw()
				uni.showToast({
					icon:'loading',
					title: '生成中',
					duration:2500
				});
			    setTimeout(() => {
			      //下面的13以及减26推测是因为在写样式的时候写了固定的zoom: 50%而没有用像素比缩放导致的黑边，所以在生成时进行了适当的缩小生成，这个大家可以自行尝试
					uni.canvasToTempFilePath({
						canvasId: 'canvasPoster',
						x: 0,
						y: 0,
						width: canvasW*pixelRatio,
						height: canvasH*pixelRatio,
						destWidth: canvasW*pixelRatio,
						destHeight: canvasH*pixelRatio,
						success: (res) => {
							console.log(res)
							this.poster = res.tempFilePath
						},
						complete(e) {
							console.log(e)
						}
					},this)
			    }, 1000)
			},
			drawText(ctx,t,x,y,w,s,h,c){
			    var chr = t.split("");
			    var temp = "";              
			    var row = [];
			    ctx.font = s+"px MicrosoftYaHei";
			    ctx.fillStyle = "black";
			    ctx.textBaseline = "middle";
			    for(var a = 0; a < chr.length; a++){
			        if( ctx.measureText(temp).width < w && ctx.measureText(temp+(chr[a])).width <= w){
			            temp += chr[a];
			        }//ctx.measureText(text).width  测量文本text的宽度
			        else{
			            row.push(temp);
			            temp = chr[a];
			        }
			    }
			    row.push(temp);
			    for(var b = 0; b < row.length; b++){
					ctx.setFillStyle(c)
			        ctx.fillText(row[b],x,y+(b*h));//字体20，间隔24。类似行高
			    }
			    // 只显示2行，加...
			    /*for(var b = 0; b < 2; b++){
			        var str = row[b];
			        if(b == 1){
			            str = str.substring(0,str.length-1) + '...';
			        }
			        context.fillText(str,x,y+(b+1)*24);
			    }*/
			},
			previewImg () {
			    if (this.poster) {
			      //预览图片，预览后可长按保存或者分享给朋友
			      uni.previewImage({
			        urls: [this.poster]
			      })
			    }
			},
			savePoster () {//小程序保存图片
			    if (this.poster) {
			      uni.saveImageToPhotosAlbum({
			        filePath: this.poster,
			        success: (result) => {
						uni.showToast({
							title: '海报已保存，快去分享给好友吧。',
							icon: 'none'
						})
			        }
			      })
			    }
			}
		}
	}
</script>

<style>
	.fenxall{
		position: fixed;
		top: 0;
		left: 0;
		z-index: 9999;
		height: 100vh;
		width: 750rpx;
	}
	.title{
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: rgba(0,0,0,0.5);
		height: 100vh;
		width: 750rpx;
	}
	.poster-img{
		width: 300px;
		height: 1000rpx;
	}
	.save-btn{
		width:347upx;
		height:81upx;
		line-height: 81upx;
		background:rgba(0, 140, 255, 1);
		border-radius:8upx;
		font-size:28upx;
		font-family:Microsoft YaHei;
		font-weight:400;
		color:#fff;
		text-align: center;
		position: absolute;
		bottom: 25upx;
		left: 50%;
		margin-left: -173.5upx;
	}
	.canvas-poster{
	  background-color: #fafafa;
	  zoom: 50%;
	  position: absolute;
	  top: -10000px;
	  background: #fafafa;
	}
</style>
